package cqie.edu.homework2.controller;

import cqie.edu.homework2.domain.po.TUser;
import cqie.edu.homework2.domain.po.TUserDetail;
import cqie.edu.homework2.service.TUserDetailService;
import cqie.edu.homework2.service.TUserService;
import cqie.edu.homework2.util.EncryptionUtil;
import cqie.edu.homework2.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
// src/main/java/com/example/demo/LoginController.java
@Controller
public class LoginController {

    @Autowired
    TUserService userService;

    @Autowired
    TUserDetailService userDetailService;

    // 显示登录页面 (GET请求)
    @GetMapping("/login")
    public String showLoginForm(Model model) {
        model.addAttribute("user", new TUser()); // 关键！绑定空对象到表单
        return "login1";
    }

    // 处理登录 (POST请求)
    @PostMapping("/login")
    public String handleLogin(
            @ModelAttribute("user") TUser tuser, // 自动绑定表单数据
            BindingResult result
    ) throws Exception {
        String password = EncryptionUtil.decrypt(tuser.getPassword());
        tuser.setPassword(password);
        if (userService.verUser(tuser)) {
            return "redirect:/home"; // 登录成功重定向
        }
        return "login1"; // 登录失败返回表单页
    }



    // 显示注册页面 (GET请求)
    @GetMapping("/register")
    public String showRegisterForm(Model model) {
        model.addAttribute("user", new TUser()); // 关键！绑定空对象到表单
        model.addAttribute("userdl", new TUserDetail());
        return "register1";
    }

    // 处理登录 (POST请求)
    @PostMapping("/register")
    public String handleRegister(
            @ModelAttribute("user") TUser user, // 自动绑定表单数据
            @ModelAttribute("userdl") TUserDetail tuserDetail,
            BindingResult result
    ) throws Exception {
        String password = EncryptionUtil.decrypt(user.getPassword());
        String vpassword = MD5.MD5encrypt(password);
        user.setPassword(password);
        //通过主键回显，在插入user的同时获取主键id
        userService.insert1(user);
        //将用户详细信息插入
        tuserDetail.setUserId(user.getId());
        userDetailService.insert(tuserDetail);

        //数据插入逻辑后续更新
        return "login1"; // 注册成功 转登录界面
    }

    // 登录成功页面
    @GetMapping("/home")
    public String home() {
        return "home1";
    }
}